<?php
/* 
 * This class provides baisc connectivity to a mysql databse.
 * It also provides helper functions to execute SQL statements.
 * it assumes that the include paths are set appropriately.
 */
class Database {
    /**
     *
     * @db connection ressource to the database.
     * @connected whether a connection to the DBMS has been successfully established.
     */
    private $db = 0;
    private $connected = false;
    private $dbms = "mysql";

    /**
     * Connects this database object to a mysql database.
     *
     * @param String $host full path to server
     * @param String $dbName name of the database
     * @param String $user user login
     * @param String $pass user password for this connection
     * @return true if successfully connected false if not.
     */
    public function connect($host, $dbName, $user, $pass) {
	$this->db = @mysql_connect($host,$user,$pass);
	if(!$this->db) {
            @include_once('install.inc');
//            echo"Did you run the <a href='install/Install.php'>installation script</a> which <br>";
//            echo"will help establish a connection to your database from the 2DBV2 application?<br>";
            $this->connected = false;
            return(false);
	}
	$rs = @mysql_query("USE $dbName");
	if(!$rs) {
            $dbName="";
            $this->connected = false;
            return(false);
	}//INSERT
        $this->connected = true;
        return(true);
    }

    /**
     * Returns whether the database object is connected or not.
     * @return boolean (true or false).
     */
    public function isConnected() {
        return($this->connected);
    }

    /**
     * An arbitrary sql statement is executed. No result is returned.
     * @param String $statement
     * @return The result of mysql is directly returned.
     */
    public function executeSQL($statement) {
        $rs = mysql_query($statement);
        return($rs);
    }

    /**
     * An arbitrary SQL statement is executed but amended with
     * LIMIT start, num
     * if start and num are provided and if start>=0 and num > 0.
     * @param String $query
     * @param int $start
     * @param int $num
     * @return String[String[]]
     * An array of associative arrays is returned.
     * 
     */
    public function getResult($query, $start=-1, $num=-1) {
        $ret = false;
        if($start >=0 && $num > 0)
            $query .= " LIMIT $start, $num";
        $rs = mysql_query($query);
        if(!$rs)
            return(false);
        if(mysql_num_rows($rs) <= 0)
            return(false);
        $i=0;
        while ($row = mysql_fetch_array($rs, MYSQL_BOTH)) {
            $ret[$i++] = $row;
        }
        return $ret;
    }

    /**
     * Loops through all classes that represent tables in the database 
     * instantiates them and checks if they are installable
     * then calls createTable and insertInitialData on the object.
     *
     */
    public function createTableSpace($pathadjust) {
        $path = __FILE__;
        if($pathadjust != "")
            $dir = "{$pathadjust}dba/{$this->dbms}";
        else
            $dir = str_replace("database.inc", "", $path);
        $dh = opendir($dir);
        while (false !== ($file = readdir($dh))) {
            $fp = "$dir/$file";
            if(strstr($fp, "database.inc")!==false)
                continue;
//            if(strstr($fp, "user.inc")===false)
//                continue;
            if (!is_dir($fp)) {
                echo"\r\n$fp-";
                include_once $fp;
                $table = $className;
                echo"$table:";
                $obj = new $table($this);
                if(method_exists($obj, "createTable")) {
                    if($obj->createTable())
                        $obj->insertInitialData();
                    else
                        echo"There was a problem creating $table<br />\r\n";
                } else
                    echo" not supported $table <br>\r\n";

                unset($obj);
                unset($table);
                unset($className);
            }
        }
        echo"\r\n\r\nDone creating table space\r\n\r\n";
    }

    /**
     * Attempts to retrieve the table list from the current database connection.
     * If tables exist and if there seem to be enough tables true is returned.
     * @return <type>
     */
    public function tableSpaceExits() {
        $res = getResult("SHOW TABLES");
        if($res && count($res) > 30 && count($res) < 40)
            return(true);
        return(false);
        // TODO a couple table names or all could be tested.
    }

    /**
     * This function creates a User object and gets all admins 
     * If at least one exists true is returned.
     */
    public function hasAdmin() {
        @include_once('user.inc');
        $users = new Users($this);
        $admins = $users->getAdmins();
        if(!$admins)
            return(false);
        if(count($admins) >= 1)
            return(true);
        return(false);
    }

    /**
     * Getter functions follow
     */
    public function getDbms() {
        return($this->dbms);
    }
    public function getDBResID() {
        return($this->db);
    }
}
?>
